extends Node2D


onready var remove_card_tween_controller: Tween = get_node("RemoveCardTween")

const DECK_CARD_REMOVE_ANIMATION_TIME: float = 0.5

var cards: Array = []

signal card_removed

func _ready() -> void:
    cards.clear()
    pass

func _draw():
    if OS.is_debug_build():
        draw_rect(Rect2(-70, -150, 140, 250), Color(0, 0, 1, 1), false)

func generate_deck(size: int) -> void:
    var available_cards: Array = CardFactory.card_datas.keys()
    var s: int = available_cards.size()
    randomize()
    for i in range(size):
        var card_name: String = available_cards[randi() % s]
        var c: Card = CardFactory.create_card(card_name)
        cards.push_back(c)
        c.rotation_degrees = 90
        c.flip()
        c.set_position(Vector2(0, -1 * cards.size()))
        add_child(c)
    pass

func remove_cards_from_top(number: int, cool_down: float) -> void:
    if number >= cards.size():
        number = cards.size()

    var endpos: int = 1500
    if number > 0:
        for i in range(number):
            var c: Card = cards.pop_back()
            remove_card_tween_controller.interpolate_property(
                c,
                "position",
                c.position,
                Vector2(endpos, c.position.y),
                DECK_CARD_REMOVE_ANIMATION_TIME,
                Tween.TRANS_LINEAR,
                Tween.EASE_IN)

            remove_card_tween_controller.interpolate_property(
                c,
                "rotation_degrees",
                c.rotation_degrees,
                0,
                DECK_CARD_REMOVE_ANIMATION_TIME - 0.01,
                Tween.TRANS_LINEAR,
                Tween.EASE_IN)

            remove_card_tween_controller.start()
            yield(get_tree().create_timer(cool_down), "timeout")
        pass
    pass


func _on_card_remove_tween_completed(object, key):
    if key == ':position':
        remove_child(object)
        emit_signal('card_removed', object)
    pass
